"""
playwright的类，初始化中写好了playwright初始化的代码
之后可以继承或者干啥都行

参数：
    pPort:传入你本地打开的代理软件的port
    headless:控制无头模式的，默认是False，关闭无头模式
    Brow:选择playwright使用的浏览器种类，参数有"webkit","firefox"和"chromium"
    anony:浏览器的匿名访问开关，默认为True,默认匿名访问

使用示例在pw_spider.py文件中
"""
import random

from playwright.sync_api import sync_playwright


class PwSpider:
    """
    playwright的类，初始化中写好了playwright初始化的代码
    之后可以继承或者干啥都行

    参数：
        pPort:传入你本地打开的代理软件的port
        headless:控制无头模式的，默认是False，关闭无头模式
        Brow:选择playwright使用的浏览器种类，参数有"webkit","firefox"和"chromium"
        anony:浏览器的匿名访问开关，默认为True,默认匿名访问
    
    方法：
        stop_pw:用于关闭playwright
        get_device:获取device
    
    使用：
        继承类，然后写方法，参见example_pwClass.py
    """

    devicesName = (
    'Desktop Chrome HiDPI',
    'Desktop Edge HiDPI',
    'Desktop Firefox HiDPI',
    'Desktop Safari',
    'Desktop Chrome',
    'Desktop Edge',
    'Desktop Firefox'
    )

    def __init__(self,pPort=10809,headless=False,Brow="webkit",anony=True):
        self.headless = headless
        self.anony = anony
        self.pw = sync_playwright().start()
        ipPort = f'127.0.0.1:{pPort}'
        proxy = "http://" + ipPort
        if not anony:
            if Brow == "firefox":
                Brow = "chromium"
            BROWSER = eval('self.pw.'+Brow)
            #BROWSER = eval('pw.chromium')
            self.browser = BROWSER.launch_persistent_context(
                user_data_dir=r'D:\杨博\pw_Temp',
                headless=headless,
                proxy={"server":proxy},
                #channel="msedge",
                #chromium_sandbox=True
            )
        else:
            BROWSER = eval('self.pw.'+Brow)
            self.browser = BROWSER.launch(
                headless=headless,
                proxy={"server":proxy}
            )
    
    def get_device(self,all=False):
        if self.anony:
            if not all:
                device = self.pw.devices[random.choice(self.devicesName)]
            else:
                devicesName = [name for name in self.pw.devices.keys()]
                device = self.pw.devices[random.choice(devicesName)]
        else:
            device = {}
        
        return device
        
    def stop_pw(self):
        self.pw.stop()